<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 添加 -->
    <div style="margin-top: 15px;">
      <el-button type="success" plain @click="addRoleFormVisible = true">添加角色</el-button>
    </div>
    <template>
      <el-table :data="rolesList" style="width: 100%">
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row v-for='first in scope.row.children' :key='first.id'>
              <el-col :span="4">
                <el-tag closable type="success" style="margin:4px 0">{{first.authName}}</el-tag>
              </el-col>
              <el-col :span="20">
                <el-row v-for='second in first.children' :key='second.id'>
                  <el-col :span="4">
                    <el-tag closable type="warning" style="margin:4px 0">{{second.authName}}</el-tag>
                  </el-col>
                  <el-col :span="20">
                    <el-tag closable type="info" v-for='third in  second.children' :key='third.id' style="margin:4px" @close="deleteRolePower(scope.row,third.id)">{{third.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
            <el-row v-if="scope.row.children.length===0">
              <el-col :span="24">当前角色暂时没有权限</el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index" width="50">
        </el-table-column>
        <el-table-column label="角色" prop="roleName">
        </el-table-column>
        <el-table-column label="描述" prop="roleDesc">
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-tooltip class="item" effect="dark" content="编辑" placement="top">
              <el-button type="primary" icon="el-icon-edit" plain></el-button>
            </el-tooltip>
            <el-tooltip class="item" effect="dark" content="删除" placement="top">
              <el-button type="primary" icon="el-icon-delete" plain></el-button>
            </el-tooltip>
            <el-tooltip class="item" effect="dark" content="授权角色" placement="top">
              <el-button type="primary" icon="el-icon-edit" plain @click="showaccreditUser(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </template>
    <!-- 角色授权对话框 -->
    <el-dialog title="编辑用户" :visible.sync="accreditdialogFormVisible">
      <div style="height:400px;overflow:auto;">
        <el-tree :data="powerList" show-checkbox node-key="id" ref='tree' :default-expand-all='true' :default-checked-keys="checkArr" :props="defaultProps">
        </el-tree>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="accreditdialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="accreditUserSubmit">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 添加角色对话框 -->
    <el-dialog title="编辑用户" :visible.sync="addRoleFormVisible">
      <el-form :model="addform" ref='addform' label-width="100px" :rules="rules">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addform.roleName" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="角色描述"  prop="roleDesc">
          <el-input v-model="addform.roleDesc" auto-complete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addRoleFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRoleSubmit">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {
  getRolesList,
  deleteRoleRight,
  getPowerList,
  accreditRoler,
  addRoler
} from '@/api/index.js'
export default {
  data () {
    return {
      rolesList: [],
      accreditdialogFormVisible: false,
      powerList: [],
      defaultProps: {
        children: 'children',
        label: 'authName'
      },
      roleid: '',
      checkArr: [],
      addRoleFormVisible: false,
      addform: {
        roleName: '',
        roleDesc: ''
      },
      rules: {
        roleName: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ],
        roleDesc: [{}]
      }
    }
  },
  mounted () {
    this.initList()
  },
  methods: {
    // 添加角色对话框

    // 实现添加角色功能
    addRoleSubmit () {
      addRoler(this.addform).then(res => {
        console.log(res)
        if (res.meta.status === 201) {
          this.$message({
            message: res.meta.msg,
            type: 'success'
          })
          // 重新刷新一次页面
          this.initList()
          // 关闭对话框
          this.addRoleFormVisible = false
          // 重置数据
          this.$refs['addform'].resetFields()
        } else {
          this.$message({
            message: res.meta.msg,
            type: 'error'
          })
        }
      })
    },
    // 加载角色列表
    initList () {
      getRolesList().then(res => {
        console.log(res)
        this.rolesList = res.data
      })
    },
    //   角色授权对话框显示
    showaccreditUser (row) {
      this.accreditdialogFormVisible = true
      getPowerList('tree').then(res => {
        console.log(res)
        this.powerList = res.data
      })
      //   拿到当前角色的id
      console.log(row)
      this.roleid = row.id
      //   每次开始重置checkArr的长度（重置默认选中）
      this.checkArr.length = 0
      //   拿到所有被选中的权限id
      if (row.children.length > 0) {
        row.children.forEach(first => {
          if (first.children.length > 0) {
            first.children.forEach(second => {
              second.children.forEach(third => {
                this.checkArr.push(third.id)
                // console.log(this.checkArr)
              })
            })
          }
        })
      }
    },
    // 角色授权功能实现
    accreditUserSubmit () {
      console.log(this.$refs.tree.getCheckedNodes())
      // 获取对象数组，需要的数据在每个对象中的id和rid
      var nodeArr = this.$refs.tree.getCheckedNodes()
      var idArr = nodeArr.map(value => {
        return value.id + ',' + value.pid
      })
      // console.log(idArr)
      // 把数组拆分连接（，方式）
      var strArr = idArr.join(',')
      // console.log(strArr)
      // 把字符串转化为数组
      var ridsArr = strArr.split(',')
      // console.log(ridsArr)
      // 去除重复的数据
      var tempArr = new Set(ridsArr)
      // console.log(tempArr)
      var finish = Array.from(tempArr)
      // console.log(finish)
      var rids = finish.join(',')
      // console.log(rids)
      accreditRoler({ roleid: this.roleid, rids: rids }).then(res => {
        console.log(res)
        if (res.meta.status === 200) {
          this.$message({
            message: res.meta.msg,
            type: 'success'
          })
          // 重新加载一次角色列表
          this.initList()
          // 关闭对话框
          this.accreditdialogFormVisible = false
          // 重置数据
          this.$refs.tree.setCheckedKeys([])
        } else {
          this.$message({
            message: res.meta.msg,
            type: 'error'
          })
        }
      })
    },
    //   删除指定角色的权限
    deleteRolePower (row, rightId) {
      deleteRoleRight(row, rightId).then(res => {
        console.log(res)
        // 判断删除是否成功，返回信息
        if (res.meta.status === 200) {
          this.$message({
            message: res.meta.msg,
            type: 'success'
          })
          //   重新渲染一次页面一次页面
          row.children = res.data
        } else {
          this.$message({
            message: res.meta.msg,
            type: 'error'
          })
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.demo-table-expand {
  font-size: 0;
}
.demo-table-expand label {
  width: 90px;
  color: #99a9bf;
}
.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 50%;
}
</style>
